package threadpoolnio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @author ：xx
 * @date ：Created in 2020/3/12 10:55
 * @description：
 * @modified By：
 */
public class ChannelClient {
    public static void main(String[] args) {
        SocketChannel socketChannel=null;
        ByteBuffer buff=ByteBuffer.allocate(1024);
        try {
            socketChannel=SocketChannel.open();
            //设置通道为非阻塞式
            socketChannel.configureBlocking(false);
            socketChannel.connect(new InetSocketAddress("127.0.0.1",9999));
            if(socketChannel.finishConnect()){
                int i=0;
                Scanner in=new Scanner(System.in);
                String msg=null;
                while ((msg=in.nextLine())!=null){
                    if(msg.equals("q"))
                        break;
                    buff.clear();
                    //向缓冲区写数据
                    buff.put(msg.getBytes("GBK"));
                    buff.flip();
                    while (buff.hasRemaining()){
                        socketChannel.write(buff);
                        //加上一个换行符
                        socketChannel.write(ByteBuffer.wrap("\r\n".getBytes()));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(socketChannel!=null)
                    socketChannel.close();
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }

    }
}
